/**
 * Copyright HCP Technology 
 * www.hcp.vn
 */
package controllers;

import play.*;
import play.modules.gae.GAE;
import play.mvc.*;
import util.SimpleCache;

import java.util.*;

import models.*;

public class Application extends Controller {

	@Before
	public static void checkLogin(){
		if(GAE.isLoggedIn()){
			Logger.info("------start user login-----");
			Logger.info("request.remoteAddress  >> " + request.remoteAddress);
			boolean flagUserActive = false;
			UserModel userModel = UserModel.getUserModelByEmail(GAE.getUser().getEmail());
			if( userModel == null){
				new UserModel(GAE.getUser().getEmail(), GAE.getUser().getNickname(), GAE.getUser().getUserId(), true).insert();
				Logger.info("---add user to Usermodel ok-");
				flagUserActive = true;
			}else{
				UserModel.setDateLogin(userModel);
				flagUserActive = userModel.isActive;
			}
			if(flagUserActive){
				renderArgs.put("user", GAE.getUser().getEmail());	
			}else{
				renderArgs.put("user", null);
			}
		}
		List<CategoryNode> categories = SimpleCache.listCategories();
		renderArgs.put("categories", categories);
	}
	
    public static void index() {
        render();
    }
    
    public static void login(){
    	Logger.info("---------login-------------");
		GAE.login("Content.create");	
    }
    
    public static void logout(){
    	Logger.info("----------logout------------");
    	GAE.logout("Application.index");
    }
    
    public static String getUser(){
    	if(renderArgs.get("user") != null && renderArgs.get("user") != ""){
    		return (String)renderArgs.get("user");
    	}
    	return null;
    }
    
    public static void tos() {
    	render();
    }

}